package com.stock.stockana.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.stock.publiclib.BaseActivity;
import com.stock.publiclib.model.UserService;
import com.stock.publiclib.utils.StringUtil;
import com.stock.stockana.R;
import com.stock.stockana.StockCenter;
import com.stock.stockana.beans.ResponseBean;
import com.stock.stockana.beans.StockInfoBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.events.StockListChangedEvent;
import com.stock.stockana.events.network.AddStockEvent;
import com.stock.stockana.events.network.DeleteStockEvent;
import com.stock.stockana.events.network.GetOneStockEvent;
import com.stock.stockana.requests.GetAllStocks;
import com.stock.stockana.requests.GetOneStock;
import com.stock.stockana.requests.GetPushRecord;
import com.stock.stockana.requests.GetRecStocks;
import com.stock.stockana.ui.fragments.CollectStockFragment;
import com.stock.stockana.ui.fragments.PushRecordsFragment;
import com.stock.stockana.ui.fragments.RecomStockFragment;
import com.stock.stockana.ui.fragments.StockListFragment;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

/**
 *---------------------------------------------------
 * Description: app主界面activity
 * Author: ljgsonx
 * Belong to: com.stock.stockana
 * Time: 2016/1/23 23:50
 *---------------------------------------------------
 */
public class MainActivity extends BaseActivity {

    private final static String TAG = "MainActivity--->";

    public static MainActivity instance;

    private StockListFragment stockListFragment;
    private RecomStockFragment recomStockFragment;
    private CollectStockFragment collectStockFragment;
    private PushRecordsFragment pushRecordsFragment;

    private String mPushedStockNum;

    NavigationView.OnNavigationItemSelectedListener mNaviItemClickedListener = new NavigationView.OnNavigationItemSelectedListener(){

        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            int itemId = item.getItemId();
            switch (itemId) {
                case R.id.nav_menu_setting:
                    startActivity(new Intent(MainActivity.this, SettingActivity.class));
                    overridePendingTransition(R.anim.in_from_right,R.anim.out_from_left);
                    getDrawerLayout().closeDrawers();
                    break;
                case R.id.nav_menu_categories:
                    startActivity(new Intent(MainActivity.this, VersionNoticeActivity.class));
                    overridePendingTransition(R.anim.in_from_right,R.anim.out_from_left);
                    getDrawerLayout().closeDrawers();
                    break;
                case R.id.nav_menu_feedback:
                    startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
                    overridePendingTransition(R.anim.in_from_right,R.anim.out_from_left);
                    getDrawerLayout().closeDrawers();
                    break;
                case R.id.nav_menu_loginOut:
                    StockCenter.getUserDB().saveToken("");
                    StockCenter.getUserDB().saveKeyValue("tempUserName", "");
                    startActivity(new Intent(MainActivity.this, SignInActivity.class));
                    overridePendingTransition(R.anim.in_from_right,R.anim.out_from_left);
                    finish();
                    instance = null;
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPushedStockNum = getIntent().getStringExtra("pushedStockNum");
        instance = this;
        initTabWithViewPager();
        initNavigation();
        setOnNavigationItemClicked(mNaviItemClickedListener);
        changeTabsFont();
        EventBus.getDefault().register(this);
        final TabLayout tabLayout = getTabLayout();
        TabLayout.Tab tab = tabLayout.getTabAt(3);
        View tabView = LayoutInflater.from(this).inflate(R.layout.push_record_tab_layout, null, false);
        tab.setCustomView(tabView);
        setmOnPageSelectedListener(new OnPageSelectedListener() {
            @Override
            public void OnPageSelected(int position) {
                for (int i = 0; i < tabLayout.getTabCount(); i++) {
                    TabLayout.Tab tab = tabLayout.getTabAt(i);
                    View customView = tab.getCustomView();
                    if (customView != null) {
                        if(customView instanceof ViewGroup){
                            for (int j = 0; j < ((ViewGroup) customView).getChildCount(); j++) {
                                if (((ViewGroup) customView).getChildAt(j) instanceof TextView) {
                                    if(position == 3){
                                        ((TextView) ((ViewGroup) customView).getChildAt(j)).setTextColor(getResources().getColor(com.stock.publiclib.R.color.c_light_white));
                                    }else{
                                        ((TextView) ((ViewGroup) customView).getChildAt(j)).setTextColor(getResources().getColor(com.stock.publiclib.R.color.c_light_gray5));
                                    }
                                }
                            }
                        }else if(customView instanceof TextView){
                            if(position == 3) {
                                ((TextView) customView).setTextColor(getResources().getColor(com.stock.publiclib.R.color.c_light_white));
                            }else {
                                ((TextView) customView).setTextColor(getResources().getColor(com.stock.publiclib.R.color.c_light_gray5));
                            }
                        }
                    }
                }
                if (position == 3 && tabLayout.getTabAt(3) != null) {
                    View view = tabLayout.getTabAt(3).getCustomView();
                    if (view != null) {
                        ImageView iv = (ImageView) view.findViewById(R.id.pushRecordRedPointIv);
                        iv.setVisibility(View.GONE);
                        SharedPreferences sharedPreference = getSharedPreferences("property", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreference.edit();
                        long newRecordDate = 0;
                        if(GetPushRecord.pushRecords.size() != 0){
                            newRecordDate = GetPushRecord.pushRecords.get(0).getWakedDate().getTime();
                        }
                        editor.putLong("lastPushRecordDate", newRecordDate);
                        editor.apply();
                    }
                }
            }
        });
    }

    public void showPushedStockIfNeed(StockInfoBean sb) {
        if(!StringUtil.isBlank(mPushedStockNum)){
            Intent intent = new Intent(this, StockDetailActivity.class);
            intent.putExtra("clickedStock", sb);
            if(StockDetailActivity.instance != null) {
                StockDetailActivity.instance.finish();
                StockDetailActivity.instance = null;
            }
            startActivity(intent);
            overridePendingTransition(R.anim.in_from_right,R.anim.out_from_left);
            mPushedStockNum = null;
        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        String accessToken = StockCenter.getUserDB().getAccessToken();
        if (StringUtil.isBlank(accessToken)) {
            Intent intent = new Intent(MainActivity.this, SignInActivity.class);
            startActivity(intent);
            overridePendingTransition(R.anim.in_from_left, R.anim.out_from_right);
            finish();
        }
        Intent intent = getIntent();
        String flag = intent.getStringExtra("fromStockDetail");
        if (!StringUtil.isBlank(flag) && "1".equals(flag)) {
            getViewPager().setCurrentItem(1);
        }
    }

    private void initTabWithViewPager() {
        List<Fragment> fragmentList = new ArrayList<>();
        stockListFragment = new StockListFragment();
        recomStockFragment = new RecomStockFragment();
        collectStockFragment = new CollectStockFragment();
        pushRecordsFragment = new PushRecordsFragment();
        if (!StringUtil.isBlank(mPushedStockNum)) {
            Bundle bundle = new Bundle();
            bundle.putString("pushedStockNum",mPushedStockNum);
            stockListFragment.setArguments(bundle);
        }
        fragmentList.add(stockListFragment);
        fragmentList.add(recomStockFragment);
        fragmentList.add(collectStockFragment);
        fragmentList.add(pushRecordsFragment);
        String[] tabTitles = getResources().getStringArray(R.array.tab_titles);
        setFragmentsWithTabs(fragmentList, tabTitles);
        int pushInt = getIntent().getIntExtra("push",0);
        if(pushInt == 1){
            getViewPager().setCurrentItem(4);
        }
    }

    private void initNavigation() {
        UserService userService = StockCenter.getUserDB();
        String tempUserName = userService.getValue("tempUserName");
        if (!StringUtil.isBlank(tempUserName)) {
            setNaviUserName(tempUserName);
            return;
        }
        String userName = userService.getUserPhoneNum();
        if (StringUtil.isBlank(userName)) {
            userName = userService.getUserEmail();
            if (!StringUtil.isBlank(userName)) {
                setNaviUserName(userName);
            }
        } else {
            setNaviUserName(userName);
        }
    }

    private void changeTabsFont() {
        ViewGroup vg = (ViewGroup) getTabLayout().getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
                if (tabViewChild instanceof TextView) {
                    ((TextView) tabViewChild).setTypeface(Typeface.createFromAsset(getAssets(), "fonts/hwxs.ttf"), Typeface.NORMAL);
                }
            }
        }
    }

    @Override
    public void onPageSelected(int position) {
        StockCenter.cancelReq(GetRecStocks.getTagStr());
        stopPopLoading();
        super.onPageSelected(position);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == com.stock.publiclib.R.id.action_search) {
            startActivity(new Intent(this,SelectStockActivity.class));
            overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(com.stock.publiclib.R.menu.menu_search, menu);
        return true;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    /**
     * Description: 添加股票后,在这里接收网络返回的信息
     * Author: ljgsonx
     * Time: 2016/1/23 19:02
     */
    @Subscribe
    public void onEventMainThread(AddStockEvent event){
        ResponseBean rb = event.getmResponseBean();
        if (rb.getRespCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            GetOneStock gos = GetOneStock.build().setStockNum(event.getDealedStockNum()).setAction(GetOneStock.ACTION_ADDSTOCK);
            StockCenter.doReq(gos);
        }else {
            stopPopLoading();
            Log.d(TAG, rb.getErrorMsg());
            Toast.makeText(this, "添加失败,请重试!", Toast.LENGTH_SHORT).show();
            StockListChangedEvent slce = new StockListChangedEvent();
            slce.setEventCode(StockListChangedEvent.EVENTCODE_ADD_FAILED);
            EventBus.getDefault().post(slce);
        }
    }

    /**
     * Description: 删除股票后,在这里接收网络返回的信息
     * Author: ljgsonx
     * Time: 2016/1/23 19:02
     */
    @Subscribe
    public void onEventMainThread(DeleteStockEvent event){
        ResponseBean rb = event.getmResponseBean();
        stopPopLoading();
        StockListChangedEvent slce = new StockListChangedEvent();
        if (rb.getRespCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            String deletedStockNum = event.getDealedStockNum();
            int addedIndex = -1;
            for (int i = 0; i < GetAllStocks.stocks.size(); i++) {
                if (GetAllStocks.stocks.get(i).getStNum().equals(deletedStockNum)) {
                    addedIndex = i;
                    break;
                }
            }
            if(addedIndex != -1) {
                GetAllStocks.stocks.remove(addedIndex);
            }
            //通知主列表页,查看叫醒页面,股票搜索页面
            EventBus.getDefault().post(slce);
        }else {
            Log.d(TAG, rb.getErrorMsg());
            Toast.makeText(this, "取消失败,请重试!", Toast.LENGTH_SHORT).show();
            slce.setEventCode(StockListChangedEvent.EVENTCODE_CANCEL_FAILED);
            EventBus.getDefault().post(slce);
        }
    }

    /**
     * Description: 查询指定股票获得其全部信息的回调,
     *      将回调放在这里是由于fragment的生命周期短,需保证接收到所有event
     * Author: ljgsonx
     * Time: 2016/2/25 16:11
     */
    @Subscribe
    public void onEventMainThread(GetOneStockEvent event) {
        //过滤掉提醒记录页面点击打开股票时,获取股票详情的的响应
        if(event.getAction() == GetOneStock.ACTION_OPENSTOCK_INPUSHRECORD) return;
        stopPopLoading();
        StockListChangedEvent slce = new StockListChangedEvent();
        if (event.getResponseCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            StockInfoBean sib = JSON.parseObject(event.getmStockInfoBeanStr(), StockInfoBean.class);
            //点击打开未收藏股票的详情页时,网络查询此股票的回调处理(使用回调信息打开股票详情页)
            if(event.getAction() == GetOneStock.ACTION_OPENSTOCK){
                Intent intent = new Intent(this, StockDetailActivity.class);
                intent.putExtra("clickedStock", sib);
                startActivity(intent);
                overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
                return;
            }else if(event.getAction() == GetOneStock.ACTION_ADDSTOCK){
                //添加股票时,网络查询此股票的回调处理(将回调信息添加至自选列表中)
                int addedIndex = -1;
                for (int i = 0; i < GetAllStocks.stocks.size(); i++) {
                    if (GetAllStocks.stocks.get(i).getStNum().equals(sib.getStNum())) {
                        addedIndex = i;
                        break;
                    }
                }
                if (addedIndex == -1) {
                    GetAllStocks.stocks.add(0, sib);
                }
            }else if(event.getAction() == GetOneStock.ACTION_UPDATEPRICE){
                //设置股票提醒价格后,重新查询此股票的回调处理
                for (int i = 0; i < GetAllStocks.stocks.size(); i++) {
                    if (GetAllStocks.stocks.get(i).getStNum().equals(sib.getStNum())) {
                        GetAllStocks.stocks.set(i, sib);
                        break;
                    }
                }
            }
            //通知主列表页,查看叫醒页面,股票搜索页面
            EventBus.getDefault().post(slce);
        }else{
            Log.d(TAG, event.getMessage());
            Toast.makeText(this, "操作失败,请重试!", Toast.LENGTH_SHORT).show();
            slce.setEventCode(StockListChangedEvent.EVENTCODE_ADD_FAILED);
            EventBus.getDefault().post(slce);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }
}
